/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.action;

import java.util.List;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.HttpResponse;
import org.zhiqim.httpd.context.extend.SwitchAction;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Ints;
import org.zhiqim.kernel.util.Longs;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.ZmrConstants;
import org.zhiqim.manager.dbo.ZmrAvatar;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 操作员/系统头像管理
 */
public class AvatarAction extends SwitchAction implements ZmrConstants
{
    public void list(HttpRequest request) throws Exception
    {
        int page = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt(ZMR_PAGE_SIZE, 20);
       
        PageResult<ZmrAvatar> result = ORM.table().page(ZmrAvatar.class, page, pageSize, new Selector("avatarType", 0));
        request.setAttribute("result", result);
    }

    public void modify(HttpRequest request) throws Exception
    {
        long avatarId = request.getParameterLong("avatarId"); 
        
        ZmrAvatar avatar = ORM.table().item(ZmrAvatar.class, avatarId);
        if(avatar == null)
        {
            request.returnHistory("头像不存在，请重新选择");
            return;
        }
        request.setAttribute("avatar", avatar);
    }
    
    public void access(HttpRequest request) throws Exception
    {
        HttpResponse response = request.getResponse();
        
        //1.判断参数
        List<String> paramList = request.getParameterMatch();
        if (paramList == null || paramList.size() != 2 || 
            !Validates.isIntegerNonnegative(paramList.get(0)) || !Validates.isIntegerPositive(paramList.get(1)))
        {//匹配参数失败
            response.sendError(_400_BAD_REQUEST_);
            return;
        }
        
        int avatarSize = Ints.toInt(paramList.get(1));
        if (avatarSize != 50 && avatarSize != 100 && avatarSize != 150)
        {//不是50/100/150
            response.sendError(_400_BAD_REQUEST_);
            return;
        }
        
        long avatarId = Longs.toLong(paramList.get(0));
        if (avatarId == 0)
        {//没有头像
            response.sendRedirect(request.getRootPath(_PATH_SERVICE_RES_AVATAR_));
            return;
        }
        
        //2.查出记录
        Selector selector = new Selector();
        selector.addFields("avatarTime, avatar"+avatarSize);
        selector.addMust("avatarId", avatarId);
        
        ZmrAvatar avatar = ORM.table().item(ZmrAvatar.class, selector);
        if (avatar == null)
        {
            response.sendError(_404_NOT_FOUND_);
            return;
        }
        
        //3.清除缓存设置
        response.removeHeader(_PRAGMA_);
        response.removeHeader(_P3P_);
        response.removeHeader(_CACHE_CONTROL_);
        
        //4.判断是否未修改
        long lastModified = avatar.getAvatarTime();
        String lastModifiedTime = DateTimes.getDateTimeHttp(lastModified);
        String ifModifiedSince = request.getHeader(_IF_MODIFIED_SINCE_);
        if (ifModifiedSince != null && ifModifiedSince.indexOf(lastModifiedTime) != -1)
        {//时间相等
            response.setHeader(_EXPIRES_, DateTimes.getDateTimeHttpNextHour());
            response.sendError(_304_NOT_MODIFIED_);
            return;
        }
        
        //5.提交修改
        response.setContentType("image/png");
        response.setHeader(_ACCEPT_RANGES_, _BYTES_);
        response.setHeader(_LAST_MODIFIED_, lastModifiedTime);
        response.setHeader(_EXPIRES_, DateTimes.getDateTimeHttpNextHour());
        
        byte[] data = null;
        switch (avatarSize)
        {
        case 50:data = avatar.getAvatar50();break;
        case 100:data = avatar.getAvatar100();break;
        case 150:data = avatar.getAvatar150();break;
        }
        
        response.write(data);
        response.commit();
    }
}
